package com.itheima.logdemo.web;

import com.itheima.logdemo.utils.LogInfo;
import com.itheima.logdemo.utils.LogUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨服务api日志采集
 */
@RequestMapping("/api")
@RestController
public class ApiController {
    
    private final Logger logger = LoggerFactory.getLogger("kafka");
    
    @Autowired
    private ApiService apiService;
    
    // @LogInfo
    @GetMapping("/kafka-test")
    public Object test() {
        // LogBean logBean = new LogBean("a", "b", "c");
        // LogUtil.setLocalInstance(logBean);
        LogUtil.log("this is a test");
        return "this is a test";
    }
    
    /**
     * 日志记录测试接口
     */
//    @LogInfo
    @GetMapping("/info-test")
    public Object info(@RequestParam int id) throws InterruptedException {
        
        LogUtil.log("I am controller");
        
        //service层调用，验证跨threadlocal的上下文日志信息传递
        return apiService.getUser(id);
    }
    
    @GetMapping("/hystrix-test")
    @HystrixCommand(fallbackMethod = "getError")
    public Object hytest(@RequestParam int id) throws InterruptedException {
        
        LogUtil.log("hystrix controller");
        System.out.println("controller:" + Thread.currentThread().getName());
        //service层调用，验证跨hystrix上下文
        int i = 1 / 0;
        return apiService.hystrixTest();
    }
    
    public String getError(int id) {
        LogUtil.log("断路器启动");
        System.out.println("fallback:" + Thread.currentThread().getName());
        return "断路器fallback";
    }
    
    /**
     * 登陆
     * cookie方式记录用户信息
     * sid记录进日志
     */
    @LogInfo
    @GetMapping("/login-test")
    public String login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) {
        
        //实际业务：从数据库验证用户名密码，省略……
        
        Cookie cookie = new Cookie("sid", username);
        //设置path，让所有请求均可以获取
        cookie.setPath("/");
        response.addCookie(cookie);
        return "success";
        
    }
}
